package com.campus.utils;

import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;

import static com.aliyun.teautil.Common.toJSONString;

import java.util.Map;

/**
 * @author TaiZai
 * @data 2024/11/19 9:30
 */
@Slf4j
public class AliyunSmsUtils {

    public static Client createClient() throws Exception {
        Config config = new Config()
                // 配置 AccessKey ID，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // 配置 AccessKey Secret，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));

        // 配置 Endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";

        return new Client(config);
    }

    public static Boolean sendSms(Map<String,String> map) throws Exception {
        boolean flag = false;
        Client client = AliyunSmsUtils.createClient();
        SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(map.get("signName"))
                .setTemplateCode(map.get("templateCode"))
                .setPhoneNumbers(map.get("phoneNumbers"))
                .setTemplateParam(map.get("templateParam"));
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);

            Integer statusCode = response.getStatusCode();
            if(statusCode != null && statusCode == 200) {
                flag = true;
            } else {
                System.out.println("短信发送失败，状态码：" + statusCode);
            }
        } catch (TeaException error) {
            // TeaException 异常捕获块
            // 记录异常信息到日志
            log.error("发送短信时发生 TeaException 异常：", error);
            // 可以根据实际情况进行其他处理，如发送告警邮件等
        } catch (Exception _error) {
            // 捕获其他类型的异常
            // 记录异常信息到日志
            log.error("发送短信时发生未知异常：", _error);
            // 可以根据实际情况进行其他处理，如发送告警邮件等
        }
        return flag;
    }

}
